package com.github.szhittech;



import com.github.szhittech.service.task.impl.UploadTask;
import com.github.szhittech.util.Logc;

import org.gradle.api.Action;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.Dependency;
import org.gradle.api.artifacts.ModuleVersionIdentifier;
import org.gradle.api.artifacts.dsl.RepositoryHandler;
import org.gradle.api.artifacts.maven.Conf2ScopeMappingContainer;
import org.gradle.api.artifacts.maven.MavenPom;
import org.gradle.api.artifacts.maven.MavenResolver;
import org.gradle.api.internal.artifacts.ImmutableModuleIdentifierFactory;
import org.gradle.api.internal.artifacts.Module;
import org.gradle.api.internal.artifacts.configurations.ConfigurationInternal;
import org.gradle.api.internal.artifacts.dsl.DefaultRepositoryHandler;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.DefaultProjectPublication;
import org.gradle.api.internal.artifacts.ivyservice.projectmodule.ProjectPublicationRegistry;
import org.gradle.api.internal.artifacts.mvnsettings.LocalMavenRepositoryLocator;
import org.gradle.api.internal.artifacts.mvnsettings.MavenSettingsProvider;
import org.gradle.api.internal.file.FileResolver;
import org.gradle.api.internal.plugins.DslObject;
import org.gradle.api.internal.project.ProjectInternal;
import org.gradle.api.plugins.BasePlugin;
import org.gradle.api.plugins.Convention;
import org.gradle.api.plugins.JavaBasePlugin;
import org.gradle.api.plugins.JavaLibraryPlugin;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.plugins.MavenPluginConvention;
import org.gradle.api.plugins.MavenRepositoryHandlerConvention;
import org.gradle.api.plugins.PluginContainer;
import org.gradle.api.plugins.WarPlugin;
import org.gradle.api.publication.maven.internal.DefaultDeployerFactory;
import org.gradle.api.publication.maven.internal.DefaultMavenRepositoryHandlerConvention;
import org.gradle.api.publication.maven.internal.MavenFactory;
import org.gradle.api.tasks.Upload;
import org.gradle.configuration.project.ProjectConfigurationActionContainer;
import org.gradle.internal.Describables;
import org.gradle.internal.Factory;
import org.gradle.internal.impldep.org.apache.maven.project.MavenProject;
import org.gradle.internal.logging.LoggingManagerInternal;

import java.util.function.Consumer;

import javax.inject.Inject;

public class MavenPluginExt implements Plugin<ProjectInternal> {
    public static final int COMPILE_PRIORITY = 300;
    public static final int RUNTIME_PRIORITY = 200;
    public static final int TEST_COMPILE_PRIORITY = 150;
    public static final int TEST_RUNTIME_PRIORITY = 100;

    public static final int PROVIDED_COMPILE_PRIORITY = COMPILE_PRIORITY + 100;
    public static final int PROVIDED_RUNTIME_PRIORITY = COMPILE_PRIORITY + 150;

    public static final String INSTALL_TASK_NAME = "install";

    private Factory<LoggingManagerInternal> loggingManagerFactory;
    private FileResolver fileResolver;
    private ProjectPublicationRegistry publicationRegistry;
    private ProjectConfigurationActionContainer configurationActionContainer;
    private MavenSettingsProvider mavenSettingsProvider;
    private LocalMavenRepositoryLocator mavenRepositoryLocator;
    private ImmutableModuleIdentifierFactory moduleIdentifierFactory;

    private Project project;
    private ProjectInternal projectInternal;

    @Inject
    public MavenPluginExt(Factory<LoggingManagerInternal> loggingManagerFactory, FileResolver fileResolver,
                          ProjectPublicationRegistry publicationRegistry, ProjectConfigurationActionContainer configurationActionContainer,
                          MavenSettingsProvider mavenSettingsProvider, LocalMavenRepositoryLocator mavenRepositoryLocator,
                          ImmutableModuleIdentifierFactory moduleIdentifierFactory) {
        this.loggingManagerFactory = loggingManagerFactory;
        this.fileResolver = fileResolver;
        this.publicationRegistry = publicationRegistry;
        this.configurationActionContainer = configurationActionContainer;
        this.mavenSettingsProvider = mavenSettingsProvider;
        this.mavenRepositoryLocator = mavenRepositoryLocator;
        this.moduleIdentifierFactory = moduleIdentifierFactory;
    }

    public void apply(final ProjectInternal project) {
        this.projectInternal = project;
        this.project = project;
        project.getPluginManager().apply(BasePlugin.class);

        MavenFactory mavenFactory = project.getServices().get(MavenFactory.class);
        final MavenPluginConvention pluginConvention = addConventionObject(project, mavenFactory);
        final DefaultDeployerFactory deployerFactory = new DefaultDeployerFactory(
                mavenFactory,
                loggingManagerFactory,
                fileResolver,
                pluginConvention,
                project.getConfigurations(),
                pluginConvention.getConf2ScopeMappings(),
                mavenSettingsProvider,
                mavenRepositoryLocator);

        configureUploadTasks(deployerFactory);
        configureUploadArchivesTask();

        PluginContainer plugins = project.getPlugins();

        try {
            Class appPluginClass = Class.forName("com.android.build.gradle.AppPlugin");
            Class libraryPluginClass = Class.forName("com.android.build.gradle.LibraryPlugin");
            Class testPluginClass = Class.forName("com.android.build.gradle.TestPlugin");
            plugins.withType(appPluginClass, new Action<Plugin>() {
                public void execute(Plugin appPlugin) {
                    configureAndroidScopeMappings(project.getConfigurations(), pluginConvention.getConf2ScopeMappings());
                }
            });
            plugins.withType(libraryPluginClass, new Action<Plugin>() {
                public void execute(Plugin libraryPlugin) {
                    configureAndroidScopeMappings(project.getConfigurations(), pluginConvention.getConf2ScopeMappings());
                }
            });
            plugins.withType(testPluginClass, new Action<Plugin>() {
                public void execute(Plugin testPlugin) {
                    configureAndroidScopeMappings(project.getConfigurations(), pluginConvention.getConf2ScopeMappings());
                }
            });
        }
        catch( ClassNotFoundException ex ) { }

        plugins.withType(JavaPlugin.class, new Action<JavaPlugin>() {
            public void execute(JavaPlugin javaPlugin) {
                configureJavaScopeMappings(project.getConfigurations(), pluginConvention.getConf2ScopeMappings());
            }
        });
        plugins.withType(JavaBasePlugin.class, new Action<JavaBasePlugin>() {
            public void execute(JavaBasePlugin javaPlugin) {
                configureInstall(project);
            }
        });
        plugins.withType(WarPlugin.class, new Action<WarPlugin>() {
            public void execute(WarPlugin warPlugin) {
                configureWarScopeMappings(project.getConfigurations(), pluginConvention.getConf2ScopeMappings());
            }
        });
        plugins.withType(JavaLibraryPlugin.class, new Action<JavaLibraryPlugin>() {
            @Override
            public void execute(JavaLibraryPlugin javaLibraryPlugin) {
                configureJavaLibraryScopeMappings(project.getConfigurations(), pluginConvention.getConf2ScopeMappings());
            }
        });
    }

    private void configureUploadTasks(final DefaultDeployerFactory deployerFactory) {
        project.getTasks().withType(Upload.class, new Action<Upload>() {
            public void execute(Upload upload) {
                RepositoryHandler repositories = upload.getRepositories();
                DefaultRepositoryHandler handler = (DefaultRepositoryHandler) repositories;
                DefaultMavenRepositoryHandlerConvention repositoryConvention = new DefaultMavenRepositoryHandlerConvention(handler, deployerFactory);
                new DslObject(repositories).getConvention().getPlugins().put("maven", repositoryConvention);
            }
        });
    }

    /**
     * #clife#============configureUploadArchivesTask===getArtifactId>>>>>>hetxxxsdk
     * #clife#============configureUploadArchivesTask===getGroupId>>>>>>com.github.szhittech
     * #clife#============configureUploadArchivesTask===getVersion>>>>>>0.0.1-SNAPSHOT
     * #clife#============configureUploadArchivesTask===getName>>>>>>hetxxxsdk
     * #clife#============configureUploadArchivesTask===getGroup>>>>>>hetgradlesdk
     * #clife#============configureUploadArchivesTask===getVersion>>>>>>unspecified
     */
    private void configureUploadArchivesTask() {
        configurationActionContainer.add(new Action<Project>() {
            public void execute(Project project) {
                Upload uploadArchives = project.getTasks().withType(Upload.class).findByName(BasePlugin.UPLOAD_ARCHIVES_TASK_NAME);
                if (uploadArchives == null) {
                    return;
                }

                ConfigurationInternal configuration = (ConfigurationInternal) uploadArchives.getConfiguration();

                Module module = configuration.getModule();
                for (MavenResolver resolver : uploadArchives.getRepositories().withType(MavenResolver.class)) {
                    MavenPom pom = resolver.getPom();

//                    pom.setGroupId("com.github.szhittech");
//                    pom.setArtifactId("hetxxxsdk");
//                    pom.setVersion("0.0.4-SNAPSHOT");



                    String group = pom.getGroupId().equals(MavenProject.EMPTY_PROJECT_GROUP_ID) ? module.getGroup() : pom.getGroupId();
                    String name = pom.getArtifactId().equals(MavenProject.EMPTY_PROJECT_ARTIFACT_ID) ? module.getName() : pom.getArtifactId();
                    String version = pom.getVersion().equals(MavenProject.EMPTY_PROJECT_VERSION) ? module.getVersion() : pom.getVersion();

                    Logc.e("============configureUploadArchivesTa>>>>>" + group+":"+name+":"+version);

                    ModuleVersionIdentifier publicationId = moduleIdentifierFactory.moduleWithVersion(group,name,version);


                    Logc.e("============configureUploadArchivesTask===getArtifactId>>>>>>" + pom.getArtifactId());
                    Logc.e("============configureUploadArchivesTask===getGroupId>>>>>>" + pom.getGroupId());
                    Logc.e("============configureUploadArchivesTask===getVersion>>>>>>" + pom.getVersion());

                    Logc.e("============configureUploadArchivesTask===getName>>>>>>" + module.getName());
                    Logc.e("============configureUploadArchivesTask===getGroup>>>>>>" + module.getGroup());
                    Logc.e("============configureUploadArchivesTask===getVersion>>>>>>" + module.getVersion());


                    publicationRegistry.registerPublication(projectInternal, new DefaultProjectPublication(Describables.withTypeAndName("Maven repository", resolver.getName()), publicationId, true));
                }
            }
        });
    }

    private MavenPluginConvention addConventionObject(ProjectInternal project, MavenFactory mavenFactory) {
        MavenPluginConvention mavenConvention = new MavenPluginConvention(project, mavenFactory);
        Convention convention = project.getConvention();
        convention.getPlugins().put("maven", mavenConvention);
        return mavenConvention;
    }

    private void configureAndroidScopeMappings(ConfigurationContainer configurations, Conf2ScopeMappingContainer mavenScopeMappings) {
        mavenScopeMappings.addMapping(COMPILE_PRIORITY, configurations.getByName(JavaPlugin.API_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.COMPILE);
        mavenScopeMappings.addMapping(COMPILE_PRIORITY, configurations.getByName(JavaPlugin.COMPILE_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.COMPILE);
        mavenScopeMappings.addMapping(RUNTIME_PRIORITY, configurations.getByName(JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.RUNTIME);
        mavenScopeMappings.addMapping(TEST_COMPILE_PRIORITY, configurations.getByName(JavaPlugin.TEST_COMPILE_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.TEST);
        mavenScopeMappings.addMapping(TEST_RUNTIME_PRIORITY, configurations.getByName(JavaPlugin.TEST_IMPLEMENTATION_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.TEST);
    }

    private void configureJavaScopeMappings(ConfigurationContainer configurations, Conf2ScopeMappingContainer mavenScopeMappings) {
        mavenScopeMappings.addMapping(COMPILE_PRIORITY, configurations.getByName(JavaPlugin.COMPILE_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.COMPILE);
        mavenScopeMappings.addMapping(RUNTIME_PRIORITY, configurations.getByName(JavaPlugin.RUNTIME_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.RUNTIME);
        mavenScopeMappings.addMapping(RUNTIME_PRIORITY, configurations.getByName(JavaPlugin.IMPLEMENTATION_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.RUNTIME);
        mavenScopeMappings.addMapping(TEST_COMPILE_PRIORITY, configurations.getByName(JavaPlugin.TEST_COMPILE_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.TEST);
        mavenScopeMappings.addMapping(TEST_RUNTIME_PRIORITY, configurations.getByName(JavaPlugin.TEST_RUNTIME_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.TEST);
        mavenScopeMappings.addMapping(TEST_RUNTIME_PRIORITY, configurations.getByName(JavaPlugin.TEST_IMPLEMENTATION_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.TEST);
    }

    private void configureJavaLibraryScopeMappings(ConfigurationContainer configurations, Conf2ScopeMappingContainer mavenScopeMappings) {
        mavenScopeMappings.addMapping(COMPILE_PRIORITY, configurations.getByName(JavaPlugin.API_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.COMPILE);
    }

    private void configureWarScopeMappings(ConfigurationContainer configurations, Conf2ScopeMappingContainer mavenScopeMappings) {
        mavenScopeMappings.addMapping(PROVIDED_COMPILE_PRIORITY, configurations.getByName(WarPlugin.PROVIDED_COMPILE_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.PROVIDED);
        mavenScopeMappings.addMapping(PROVIDED_RUNTIME_PRIORITY, configurations.getByName(WarPlugin.PROVIDED_RUNTIME_CONFIGURATION_NAME),
                Conf2ScopeMappingContainer.PROVIDED);
    }

    private void configureInstall(Project project) {
        //Upload installUpload = project.getTasks().create(BasePlugin.UPLOAD_ARCHIVES_TASK_NAME, Upload.class);//INSTALL_TASK_NAME
        Upload installUpload = project.getTasks().create(INSTALL_TASK_NAME, Upload.class);
        Configuration configuration = project.getConfigurations().getByName(Dependency.ARCHIVES_CONFIGURATION);
        installUpload.setConfiguration(configuration);
        MavenRepositoryHandlerConvention repositories = new DslObject(installUpload.getRepositories()).getConvention().getPlugin(MavenRepositoryHandlerConvention.class);
        repositories.mavenInstaller();
        installUpload.setDescription("Installs the 'archives' artifacts into the local Maven repository.");

//        project.getTasks().all(new Action<Task>() {
//            @Override
//            public void execute(Task task) {
//                String name = task.getName();
//                if (name != null && name.equalsIgnoreCase(BasePlugin.UPLOAD_ARCHIVES_TASK_NAME)) {
//                    task.setGroup("upload");
//                }
//            }
//        });


    }
}

